<template>
  <div class="lv-select">
    <input
      type="text"
      class="lv-select__input"
      readonly
      :value="selectOption.label"
      :placeholder="placeholder"
      @focus="isShow = true"
    />

    <div class="lv-select-dropdown" v-show="isShow">
      <div
        class="lv-select-option"
        v-for="option in options"
        :key="option.value"
        :class="{ selected: myValue === option.value }"
        @click="handleChange(option)"
      >
        {{ option.label }}
      </div>
    </div>

    <select v-model="myValue" style="display:none">
      <option value disabled>请选择</option>
      <option
        v-for="option in options"
        :key="option.value"
        :value="option.value"
        >{{ option.label }}</option
      >
    </select>
  </div>
</template>

<script>
export default {
  name: "LvSelect",

  props: {
    placeholder: {
      type: String,
      default: "请选择",
    },

    value: {
      type: [String, Number],
    },

    // 下拉选项
    options: {
      type: Array,
      default() {
        return [];
      },
    },
  },

  data() {
    return {
      myValue: parseInt(this.value),
      isShow: false,
    };
  },

  computed: {
    selectOption() {
      return this.options.find((option) => option.value === this.myValue) || {};
    },
  },

  methods: {
    handleChange(option) {
      this.myValue = option.value;
      this.isShow = false;
    },
  },

  watch: {
    /**
     * 监听选择的值发生变化
     * 1. 通过 this.$emit('触发事件',当前选择的值)
     */
    myValue(newVal) {
      this.$emit("input", newVal);
    },
  },
};
</script>

<style lang="scss">
.lv-select {
  position: relative;
  display: inline-block;
  width: 240px;

  &__input {
    background-color: #ffffff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: none;
    padding: 0 15px;
    width: 100%;
    cursor: pointer;
  }
}

.lv-select-dropdown {
  width: 100%;
  min-height: 36px;
  position: absolute;
  left: 0;
  top: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  margin: 5px 0;
  padding: 5px 0;
}

.lv-select-option {
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }

  &.selected {
    color: #409eff;
    font-weight: 700;
  }
}
</style>
